<template>
    <div class="layout-app">
		<!-- main -->
			<!-- 新增 -->
		<div class="addksFile">
			<el-dialog :title="nameTitle" :visible.sync="dialogFormVisible" width="70%" :before-close="handleAddClose">
				<el-divider></el-divider>
				<!-- tabs -->
				<div class="tabs">
					<div class="tabsMain">
						<!-- tabs-left -->
						<div class="tabs-left">
							<!-- 表单 -->
							<el-form ref="form" :rules="addFormRules" :model="addForm" label-width="88px" size="mini" v-loading="loading">
								<el-row :gutter="20">
								  <el-col :span="v.spanRows" type="flex" v-for="(v,i) in formType" :key="i">
									  <!-- input -->
									  <el-form-item v-if="v.type == 'input'" :label="v.label" :prop="v.modelValue">
										<el-input v-if="v.zdy" v-autoCode="deptCode" :suffix-icon='v.prefix' v-model="$data.addForm[v.modelValue]" :disabled="v.disabled" placeholder="请输入内容"></el-input>
										<el-input v-else :suffix-icon='v.prefix' v-model="$data.addForm[v.modelValue]" @input="iname(v,i)" placeholder="请输入内容"></el-input>
									  </el-form-item>
									  <!-- select -->
									<!--  <el-form-item v-if="v.type == 'select'" :label="v.label" :prop="v.modelValue">
										<el-select v-model="$data.addForm[v.modelValue]" placeholder="请选择" @focus="sname(v,i)" @change="scname">
										    <el-option v-for="(item,index) in $data[v.op]" :key="index" :label="item.label" :value="item.id"> 
											<span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span></el-option>
										</el-select>
									  </el-form-item> -->
									  <el-form-item v-if="v.type == 'select'" :label="v.label" :prop="v.modelValue">
									    <el-select 
									      v-model="$data.addForm[v.modelValue]" 
									      placeholder="请选择" 
									      @focus="sname(v,i)" 
									      @change="scname"
									     filterable
									    >
									      <el-option 
									        v-for="(item,index) in $data[v.op]" 
									        :key="index" 
									        :label="item.label" 
									        :value="item.id"
									      > 
									        <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
									      </el-option>
									    </el-select>
									  </el-form-item>
									  <el-form-item v-if="v.type == 'selectKsName'" :label="v.label" :prop="v.modelValue">
									    <el-select 
									      v-model="$data.addForm[v.modelValue]" 
									      placeholder="请选择" 
									      @focus="sname(v,i)" 
									      @change="(val) => scname(val)"
									      filterable
									      value-key="code"
									    >
									      <el-option 
									        v-for="(item,index) in $data[v.op]" 
									        :key="index" 
									        :label="item.label" 
									        :value="item.code" 
									      > 
									        <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
									      </el-option>
									    </el-select>
									  </el-form-item>
									  <!-- date -->
									  <el-form-item v-if="v.type == 'date'" :label="v.label">
										<el-date-picker class="autoWidth" :picker-options="pickerOptions" type="date" placeholder="选择日期" v-model="$data.addForm[v.modelValue]"></el-date-picker>
									  </el-form-item>
								  </el-col>
								</el-row>
					
							</el-form>
						</div>
						<!-- tables-right -->
						<div class="tabs-right">
							<addksFileTable ref="addksFileTable" @sonData="sonData"></addksFileTable>
						</div>
					</div>
				</div>
			  <div slot="footer" class="dialog-footer" v-if="!editBtn">
				<el-button size="mini" type="primary" @click="addNewDiction" v-loading="loading">新增</el-button>
				<el-button size="mini" @click="dialogFormVisible = false">取消</el-button>
			  </div>
			  <div slot="footer" class="dialog-footer" v-if="editBtn == true">
					<el-button size="mini" type="primary" @click="editNewDiction" v-loading="loading">保存</el-button>
					<el-button size="mini" @click="dialogFormVisible = false">取消</el-button>
			  </div>
			</el-dialog>
		</div>
    </div>
</template>

<script>
// self
import addksFileType from './addksFileType.js'
// selfs / js
import Pinyin from "@/external/pinyin.js"; //中译音
// prop
import addksFileTable from './addksFileTable.vue'
// 接口
import { addDept,getDeptName,updateDept,getDeptAttribute,docclinicList } from "@/api/ks/ks.js";

import { yglist } from "@/api/staff/staff.js"; // 获取员工信息
export default {
	components:{
		addksFileType,addksFileTable,
	},
	inject: ['reload'], // 无痕刷新
	data(){
		return{
			//str
			idx:'',
			value:'',
			deptCode:'',
			clinicId:'',
			nameTitle:'',
			//num
			//ble
			loading:false,
			editBtn:false,
			dialogFormVisible:false,
			//arr
			formType:[],
			sexOptions:[{id:1,label:'男',value:'男'},{id:2,label:'女',value:'女'}],
			YNOptions:[{id:0,label:'是',value:'是'},{id:1,label:'否',value:'否'}],
			statusOptions:[{id:1,label:'可用',value:'可用'},{id:0,label:'禁用',value:'禁用'}],
			clinicOptions:[], // 隶属诊所
			fzrOptions:[], // 负责人
			specialtyNameOptions:[],
			deptTypeOptions:[
				{id:1,label:'门诊临床',value:'门诊临床'},{id:2,label:'住院临床',value:'住院临床'},{id:3,label:'医技',value:'医技'},
				{id:4,label:'行政',value:'行政'},{id:5,label:'后勤',value:'后勤'},{id:6,label:'药库',value:'药库'},
				{id:7,label:'药房',value:'药房'},{id:8,label:'其它',value:'其它'}
			],
			medicineTypeOptions:[
				{id:1,label:'西医',value:'西医'},{id:2,label:'中医',value:'中医'},{id:3,label:'民族医',value:'民族医'},
				{id:4,label:'中西医结合',value:'中西医结合'},{id:5,label:'其它',value:'其它'}
			],
			//obj
			pickerOptions: {
			  disabledDate(time) {
				return time.getTime() > Date.now();
			  },
			  shortcuts: [{
				text: '今天',
				onClick(picker) {
				  picker.$emit('pick', new Date());
				}
			  }, {
				text: '昨天',
				onClick(picker) {
				  const date = new Date();
				  date.setTime(date.getTime() - 3600 * 1000 * 24);
				  picker.$emit('pick', date);
				}
			  }, {
				text: '一周前',
				onClick(picker) {
				  const date = new Date();
				  date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
				  picker.$emit('pick', date);
				}
			  }]
			},
			addForm:{
				deptCode:'',  //科室编码
				status:'',  //有效状态
				deptName:'',  //科室名称
				pyCode:'',  //拼音简码
				personInCharge:'',  //负责人
				personInChargeTel:'',  //负责人电话
				specialtyName:'',  //科室专业
				physicalPosition:'',//物理位置
				returnVisitNum:0,  //返诊期限
				deptType:'',  //科室类型
				medicineType:'',  //医学类型
				remark:'',  //备注
				operatingUser:'',// 操作人
				clinicId:0,// 所属诊所
				// 科室属性
				departmentAttribute:[]
			},
			// 表单验证规则 header
			addFormRules:{
				deptName: [{ required: true, message: '请先选择要入库的库房！', trigger: 'change' }],
				specialtyName: [{ required: true, message: '请选择科室专业！', trigger: 'change' }],
				// 示例：号码验证
			},
		}
	},
	mounted() {
		  // 获取当前登录用户信息
		  let userInfo = JSON.parse(localStorage.getItem('userInfo'));
		  this.currentClinicId = userInfo.clinicId; // 获取当前用户的 clinicId
		  
		  // 左侧提交表单
		  this.formType = addksFileType.map(function(v) {
		    return v
		  })
		  
		  // 1、在点击新增后，从钩子函数上获取到数据
		  this.addForm.deptCode = JSON.parse(sessionStorage.getItem('deptCode'));
		  this.addForm.operatingUser = userInfo.userName;
		  this.chooseStaff();
		  this.getClinic();
		  this.getspecialtyNameOptions();
		
	},
	updated() {
	
	},

	methods:{
		async open(pamra) {
		  this.dialogFormVisible = true;
		  console.log(pamra,'pamrapamrapamra');
		  if(pamra.nameTitle == '新增' || pamra.nameTitle.includes('新增')){
			this.nameTitle = pamra.nameTitle;
			// 每次打开时重置表单并设置默认 clinicId
			this.$nextTick(() => {
			  if (this.$refs.form) {
				this.$refs.form.resetFields();
				this.addForm.clinicId = this.currentClinicId;
			  }
			});
		  }
		 else if (pamra.nameTitle == '修改' || pamra.nameTitle.includes('修改')){
		   this.nameTitle = pamra.nameTitle;
		   this.addBtn = true;
		   this.editBtn = true;
		   let res = await getDeptAttribute({ deptId:pamra.id });
		   console.log(res,'获取修改科室的档案信息');
		   if(res.code === 200){
		     // 遍历 res.data 的所有键名
		     for (let key in res.data) {
		       // 检查键名是否在对象 A 中存在
		       if (this.addForm.hasOwnProperty(key)) {
		         // 特殊处理 specialtyName
		         if (key === 'specialtyName') {
		           // 查找对应的 code
		           const specialty = this.specialtyNameOptions.find(item => 
		             item.name === res.data[key] || item.label === res.data[key] || item.code === res.data[key]
		           );
		           this.addForm[key] = specialty ? specialty.code : res.data[key];
		         } else {
		           // 其他字段正常赋值
		           this.addForm[key] = res.data[key];
		         }
		       }
		     }
			  // 将科室属性数据传递给子组件
			  this.$nextTick(() => {
				if (res.data.departmentAttribute && res.data.departmentAttribute.length > 0) {
				  this.$refs.addksFileTable.setTableData(res.data.departmentAttribute);
				}
			  });
			  this.addForm.id = pamra.id
			  
			  // 确保编辑时也使用当前用户的 clinicId
			  this.addForm.clinicId = this.currentClinicId;
			}
		  }
		},
		// 触发员工信息选择
		async chooseStaff(){
		   // 员工信息数据源
		  let res = await yglist();
			this.fzrOptions = res.data
			this.fzrOptions = this.fzrOptions.map(v=>{
				return { label:v.fullName , ...v }
			});
			// console.log(this.fzrOptions,'kkkkkkksjj');
		},
		
		// 科室专业列表
		async getspecialtyNameOptions() {
		  let res = await getDeptName({
		    name: '',
		  });
		  console.log(res.data);
		  // 修改这里：返回包含 code 和 id 的完整对象
		  this.specialtyNameOptions = res.data.map(v => { 
		    return { 
		      label: v.name, 
		      value: v.code,  // 使用 code 作为 value
		      id: v.id,      // 保留 id
		      code: v.code,  // 确保有 code 字段
		      ...v           // 保留其他属性
		    }
		  });
		},
		// 隶属诊所选择
		async getClinic(){
		  let res = await docclinicList();
		  
		  // 过滤诊所列表，只保留当前用户所属诊所
		  this.clinicOptions = res.data
		    .filter(clinic => clinic.id === this.currentClinicId)
		    .map(v => {
		      return { 
		        id: v.id,
		        label: v.name,
		        value: v.id
		      };
		    });
		  // 设置默认的 clinicId
		  this.addForm.institutionId = this.currentClinicId;
		  // 如果过滤后没有选项，可以添加提示或处理
		  if (this.clinicOptions.length === 0) {
		    console.warn('当前用户没有关联诊所或诊所不存在');
		  } else {
		    // 自动设置默认选中的诊所
		    this.addForm.clinicId = this.clinicOptions[0].id;
		  }
		},
		handleBind() {
			return this.deptCode
		  },
		// 键盘事件
		 handleKeyup(event) {
		  // 检查按键
		  if (event.key === 'Enter') {
			// 执行相应的动作
			console.log('Enter key was pressed');
		  }
		},
		// 打开model
		openModel(){
			this.dialogFormVisible = true;
		},
		//  select聚焦
		sname(v,i) {
			if(v.label == '隶属诊所' || v.label.includes('隶属')){
				this.getClinic();
			}
			// v.id = i;
			this.idx = i;
			// i event
			switch (i) {
				case 1:
					// 有效状态
					console.log('id索引为1的');
					break;
			}
		},
		scname(value) {
		  // 根据当前 idx 判断是哪个 select
		  switch (this.idx) {
		    case 1: // 有效状态
		      this.addForm.status = value;
		      break;
		    case 4: // 负责人
		      // 查找完整的负责人信息
		      const person = this.fzrOptions.find(item => item.value === value || item.id === value);
		      if (person) {
		        this.addForm.personInCharge = person.value || person.id;
		        this.addForm.personInChargeTel = person.tel || '';
		      }
		      break;
		    case 6: // 科室专业
		      // 对于 selectKsName 类型，value 已经是 code
		      this.addForm.specialtyName = value;
		      // 如果需要，可以查找完整信息
		      const specialty = this.specialtyNameOptions.find(item => item.code === value);
		      if (specialty) {
		        // 可以在这里设置其他相关字段
		      }
		      break;
		    case 9: // 科室类型
		      this.addForm.deptType = value;
		      break;
		    case 10: // 医学类型
		      this.addForm.medicineType = value;
		      break;
		  }
		},
		// inputVal to addForm
		iname(v,i){
			i = v.id
			// console.log(i,'oooooooosssss');
			// i event
			switch (i) {
				case 2:
					// 同步赋值
					setTimeout(() => {
						// 第一个输入框为科室名称
						this.addForm.pyCode = this.makePy(this.addForm.deptName).toUpperCase();//自生成编码拼接：中译音大写
					}, 888)
					break;
			}
		},
		// 控制科室属性新增model，接收子组件传递过来的值并赋值
		sonData(newVal){
			// console.log(newVal,'子子组件传过来的');
			this.addForm.departmentAttribute.push((JSON.parse(JSON.stringify(newVal))))
		},
		//新增保存
		async addNewDiction(){
		  // 确保使用当前用户的 clinicId
		  this.addForm.clinicId = this.currentClinicId;
		  
		  console.log('新增保存',this.addForm);
		  let rs = await addDept(this.addForm)
		  if (rs.code === 200){
		    this.disabled = true;
		    this.loading = true;
		    setTimeout(() => {
		      this.$message({
		        message: rs.message,
		        type: 'success',
		        duration: 2000,
		      });
		      this.loading = false;
		      this.disabled = false;
		      this.dialogFormVisible = false;
		    }, 1500)
		    this.reload();//数据重新渲染
		  }else{
		    //验证失败
		    this.$message({
		      message:rs.message,
		      type:"info"
		    });
		  }
		},
		// 修改
		async editNewDiction(){
			// 确保使用当前用户的 clinicId
			this.addForm.clinicId = this.currentClinicId;
			console.log('修改保存',this.addForm);
			let rs = await updateDept(this.addForm)
			if (rs.code === 200){
			  this.disabled = true;
			  this.loading = true;
			  setTimeout(() => {
			    this.$message({
			      message: rs.message,
			      type: 'success',
			      duration: 2000,
			    });
			    this.loading = false;
			    this.disabled = false;
			    this.dialogFormVisible = false;
			  }, 1500)
			  this.$emit('loadData') //数据重新渲染
			}else{
			  //验证失败
			  this.$message({
			    message:rs.message,
			    type:"info"
			  });
			}
		},
		handleAddClose(done) {
			this.$confirm('确认关闭？')
			  .then(_ => {
				  done();
				// this.formdisabled = true;
				// location.reload();
				// done();
			  })
			  .catch(_ => {
				this.formdisabled = this.formdisabled;
			  });
		},
	},
	
}
</script>

<style lang="less" scoped>
.layout-app{
    width: 100%;
    height: 100%;
    display: flex;
	background-color: #f8f8f8;
   .addksFile{
		/deep/ .el-dialog__header{
			padding: 12px;
			background-color: #007bb0;
		}

		/deep/ .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
			margin-bottom: 8px;
		}
		/deep/ .el-dialog__title{
			font-size: 12px;
			color: #fff;
		}
		/deep/ .el-dialog__headerbtn .el-dialog__close{
			color: #fff;
		}
		/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
			background-color: brown;
		}
		/deep/ .el-dialog__body{
			padding: 0;
		}
		/deep/ .el-divider--horizontal{
			margin: 0;
		}
		/deep/ .el-form-item__label{
			display: flex;
			justify-content: right;
			font-size: 12px;
		}
		// self
		// 选项卡
		.tabs{
			
			.tabsMain{
				display: flex;
				border: 1px solid #f4f4f4;
				.tabs-left{
					flex: 1;
					padding:12px 0 0 12px;
					border: 1px solid #e8f0ee;
					// date flex
					.autoWidth{
						width: 100%; /* 设置宽度为100% */
					}
					/deep/ .el-input__icon{
						color: brown;
					}
					/deep/ .el-input--mini .el-input__inner{
						height: 26px;
						line-height: 26px;
					}
				}
				.tabs-right{
					flex: 1;
					padding:12px;
					margin-left: 8px;
					border: 1px solid #e8f0ee;
				}
			}
			
			
		}
	}
}
</style>